#lang racket
(require rackunit
         srfi/1
         racket/set
         racket/stream
         "euler-help.rkt")

; 1.
; If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
;
; Find the sum of all the multiples of 3 or 5 below 1000.
(define (euler-1)
  (define (multiple? n)
    (if (or (zero? (remainder n 3)) (zero? (remainder n 5))) n 0))
  (define (sum-if-multiple max)
    (sum multiple? 3 add1 max))
  (sum-if-multiple 999))

; 2.
; Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
;
; 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
;
; Find the sum of all the even-valued terms in the sequence which do not exceed four million.
(define (euler-2)
  (apply + (filter even? (list-fibs-up-to 4000000))))

; 3.
; The prime factors of 13195 are 5, 7, 13 and 29.
; What is the largest prime factor of the number 600851475143 ?
(define (euler-3)
  (apply max (prime-factors 600851475143)))

; 5.
; 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
;
; What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
(define (euler-5)
  (apply lcm (for/list ([i (in-range 1 20)]) i)))

; 6.
; Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
(define (euler-6)
  (define (sum-of-squares upto)
    (sum square 1 add1 upto))
  (define (square-of-sum upto)
    (square (sum identity 1 add1 upto)))
  (abs (- (sum-of-squares 100) (square-of-sum 100))))

; 7.
; By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
;
; What is the 10001st prime number?
(define (euler-7)
  (nth-prime 10000))

;(check-equal? (euler-1) 233168)
;(check-equal? (euler-2) 4613732)
;(check-equal? (euler-3) 6857)
;(check-equal? (euler-4) 906609)
;(check-equal? (euler-5) 232792560)
;(check-equal? (euler-6) 25164150)
;(check-equal? (euler-7) 104743)


; 45. 
; Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
; 
; Triangle	 	Tn=n(n+1)/2	 	    1, 3, 6, 10, 15, ...
; Pentagonal	Pn=n(3n-1)/2	    1, 5, 12, 22, 35, ...
; Hexagonal	 	Hn=n(2n-1)	 	    1, 6, 15, 28, 45, ...
; 
; It can be verified that T285 = P165 = H143 = 40755.
(define (euler-45 [n 144])
  (let* ([hexagonal-number (* n (- (* 2 n) 1))]
         [pentagonal-index (/ (+ 1 (sqrt (+ 1 (* 24 hexagonal-number)))) 6)])
    (if (integer? pentagonal-index) hexagonal-number (euler-45 (+ n 1)))))

(time (euler-45))
